package com.kitty.game.onlinemall;

import com.kitty.game.ServerService;
import com.kitty.game.role.model.Account;
import com.kitty.game.onlinemall.model.Charge;
import com.kitty.game.onlinemall.model.Pay;
import com.kitty.game.role.model.Role;
import com.kitty.game.config.OnlineMall;
import com.kitty.common.utils.SpringUtils;
import com.kitty.game.bag.message.RespIconCartoon;
import com.kitty.game.enter.FiedValue;
import com.kitty.game.enter.RespNotifyMisc;
import com.kitty.game.enter.RespUpdate;
import com.kitty.game.equip.message.RespNotifyMiscEx;
import com.kitty.game.team.message.RespMsg;
import com.kitty.game.utils.AsktaoUtil;
import com.kitty.common.model.Reason;
import com.kitty.mina.annotation.RequestMapping;
import com.kitty.mina.cache.DataCache;
import com.kitty.mina.cache.SessionUtils;
import com.kitty.mina.message.MessagePusher;
import com.kitty.game.role.service.AccountService;
import com.kitty.game.base.service.BagService;
import com.kitty.game.role.service.RoleService;
import org.apache.mina.core.session.IoSession;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.lang.util.NutMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;


@Controller
public class OnlineMallController {

    /**
     * 购买道具
     *
     * @param session
     * @param reqBuyFromOnlineMall
     */
    @RequestMapping
    public void buyDaoju(IoSession session, ReqBuyFromOnlineMall reqBuyFromOnlineMall) {

        BagService bagService = SpringUtils.getBean(BagService.class);
        Role role = SessionUtils.getRoleBySession(session);
        RoleService roleService = SpringUtils.getBean(RoleService.class);
        ServerService serverService = SpringUtils.getBean(ServerService.class);
        if (serverService.getServer().getId() == 10000){
            MessagePusher.pushMessage(role,new RespNotifyMiscEx("跨服试道时，不能购买物品"));
            return;
        }
        /*
        roleService.updateRoleMoney(role);
        if (reqBuyFromOnlineMall.getBarcode().contains("C000000")) {//元宝兑换游戏币
            String moneyType = reqBuyFromOnlineMall.getBarcode();
            int money = 0;
            boolean isTrue = false;
            NutMap nutMap = role.getGold2money();
            int needGold = 0;
            int roleGold = role.getGold();
            int roleMoney = role.getMoney();
            if (moneyType.equals("C0000001")) {//300元宝  300W
                if (roleGold >= 300) {
                    if (!nutMap.getBoolean("1", false)) {
                        needGold = 300;
                        isTrue = true;
                        money = 3000000;
                        SpringUtils.getRoleService().subtractGold(role, 300, Reason.BUY_ITEM);
                    }
                }
            } else if (moneyType.equals("C0000002")) {//600元宝  600W
                if (!nutMap.getBoolean("2", false)) {
                    if (roleGold >= 600) {
                        needGold = 600;
                        isTrue = true;
                        money = 6000000;
                        SpringUtils.getRoleService().subtractGold(role, 600, Reason.BUY_ITEM);
                    }
                }
            } else if (moneyType.equals("C0000003")) {//1100元宝  1000W
                if (!nutMap.getBoolean("3", false)) {
                    if (roleGold >= 1100) {
                        needGold = 1100;
                        isTrue = true;
                        money = 10000000;
                        SpringUtils.getRoleService().subtractGold(role, 1100, Reason.BUY_ITEM);
                    }
                }
            } else if (moneyType.equals("C0000004")) {//3300元宝  3000W
                if (!nutMap.getBoolean("4", false)) {
                    if (roleGold >= 3300) {
                        needGold = 3300;
                        isTrue = true;
                        money = 30000000;
                        SpringUtils.getRoleService().subtractGold(role, 3300, Reason.BUY_ITEM);
                    }
                }
            } else if (moneyType.equals("C0000005")) {//7200元宝  6000W
                if (!nutMap.getBoolean("5", false)) {
                    if (roleGold >= 7200) {
                        needGold = 7200;
                        isTrue = true;
                        money = 60000000;
                        SpringUtils.getRoleService().subtractGold(role, 7200, Reason.BUY_ITEM);
                    }
                }
            } else if (moneyType.equals("C0000006")) {//12000元宝  1E
                if (!nutMap.getBoolean("6", false)) {
                    if (roleGold >= 12000) {
                        needGold = 12000;
                        isTrue = true;
                        money = 100000000;
                        SpringUtils.getRoleService().subtractGold(role, 12000, Reason.BUY_ITEM);
                    }
                }
            }
            if (isTrue) {//代表元宝足够
                roleService.addMoney(role,money,Reason.BUY_MONEY);
                roleService.updateRoleMoney( role);
                MessagePusher.pushMessage(role, new RespNotifyMiscEx("你花费了#R" + needGold + "#n元宝，购买了" + AsktaoUtil.getMoneyFormat(money) + "#n文钱。"));
                MessagePusher.pushMessage(role, new RespIconCartoon("金钱"));
                role.save();
            } else {
                MessagePusher.pushMessage(role, new RespMsg("你今天已经购买过了，请明日再来吧。"));
            }
            return;
        }
        */

        short newPos = bagService.getPos(role, false);
        if (newPos <= 0) {
            MessagePusher.pushMessage(role, new RespMsg("你的包裹已满。"));
            return;
        }
        String number = reqBuyFromOnlineMall.getBarcode();
        int num = reqBuyFromOnlineMall.getAmount();
        if (num <= 0 || num > 100) {
            return;
        }
        OnlineMall onlineMall = DataCache.NUM_MALL.get(number);
        int count =999;
//        if (onlineMall.getName().contains("仙风散")){
//            count = SpringUtils.getActivityService().getRemainCount(role, ActivityType.cjxfs);
//        }
//        if (onlineMall.getName().contains("宠风散")){
//            count = SpringUtils.getActivityService().getRemainCount(role, ActivityType.cjcfs);
//        }
//        if (onlineMall.getName().contains("紫气鸿蒙")){
//            count = SpringUtils.getActivityService().getRemainCount(role, ActivityType.zqhm);
//        }
//        if (onlineMall.getName().contains("顿悟丹")){
//            count = SpringUtils.getActivityService().getRemainCount(role, ActivityType.cwdwd);
//        }
        if (count <=0){
            MessagePusher.pushMessage(role,new RespNotifyMiscEx("今日商城购买数量已至上线，请找#R活动大使#n购买"));
            return;
        }
        if (num > count){
            MessagePusher.pushMessage(role,new RespNotifyMiscEx("今日购买数量最多为#R2颗"));
            return;
        }
        int roleSiver = role.getSiver();
        int roleGold = role.getGold();
        int costType = onlineMall.getCosttype();
        boolean isGold = false;
        long total = new Long(onlineMall.getPrice()) * num;
        if (reqBuyFromOnlineMall.getCoin_type().equals("gold_coin")) {
            if (roleGold < total) {
                // 金元宝不足
                return;
            } else {
                //元宝可以购买
                isGold = true;
                SpringUtils.getRoleService().subtractGold(role, onlineMall.getPrice() * num, Reason.BUY_ITEM);
            }
        } else {
            if (costType == 2) {

                if (roleSiver < total) {
                    // 银币
                    if (roleGold < total) {
                        // 金元宝不足
                        return;
                    } else {
                        //元宝可以购买
                        isGold = true;
                        SpringUtils.getRoleService().subtractGold(role, onlineMall.getPrice() * num, Reason.BUY_ITEM);
                    }
                } else {
                    // 银币可以购买
                    roleService.subtractSiver(role, onlineMall.getPrice() * num, Reason.BUY_ITEM);
                }
            } else {
                // 元宝

                if (roleGold <  total ) {
                    // 金元宝不足
                    return;
                } else {
                    //元宝可以购买
                    isGold = true;
                    SpringUtils.getRoleService().subtractGold(role, onlineMall.getPrice() * num, Reason.BUY_ITEM);
                }
            }
        }
//        if (onlineMall.getName().contains("仙风散")){
//            SpringUtils.getActivityService().addFinishCount(role, ActivityType.cjxfs, num);
//        }
//        if (onlineMall.getName().contains("宠风散")){
//            SpringUtils.getActivityService().addFinishCount(role, ActivityType.cjcfs, num);
//        }
//        if (onlineMall.getName().contains("紫气鸿蒙")){
//            SpringUtils.getActivityService().addFinishCount(role, ActivityType.zqhm, num);
//        }
//        if (onlineMall.getName().contains("顿悟丹")){
//            SpringUtils.getActivityService().addFinishCount(role, ActivityType.cwdwd, num);
//        }
        String unit = onlineMall.getUnit();
        roleService.updateRoleGoldAndSiver(role);//更新角色面板金银元宝
        if(onlineMall.getName().contains("1W鬼气")){
            roleService.addGuiQi(role,10000*num,true);
            return;
        }else if(onlineMall.getName().contains("1W阴德")){
            SpringUtils.getRoleService().addYinde(role,10000*num,true);
            return;
        }else if(onlineMall.getName().contains("1W武灵值")){
            SpringUtils.getRoleService().addWuling(role,10000*num,true);
            return;
        }else if(onlineMall.getName().contains("1W洛书经验")){
            SpringUtils.getRoleService().addluoshuExp(role, 10000*num);
            return;
        }
        bagService.addRoleEquip(role, isGold, num, onlineMall);
        MessagePusher.pushMessage(session, new RespIconCartoon(onlineMall.getName()));
        RespNotifyMisc notifyMisc = new RespNotifyMisc();
        notifyMisc.setMsg("你花费#R" + onlineMall.getPrice() * num + "#n元宝购买了#R" + num + "#n" + unit + "#R" + onlineMall.getName() + "#n。");
        MessagePusher.pushMessage(role, notifyMisc);

        RespMsg respInviteMsg = new RespMsg();

        respInviteMsg.setMsg("购买成功，你得到了#R" + num + "#n" + unit + "#R" + onlineMall.getName() + "#n。");
        MessagePusher.pushMessage(role, respInviteMsg);

        RespBuyResult respBuyResult =new  RespBuyResult((short) 1,onlineMall.getNumber());
        MessagePusher.pushMessage(role,respBuyResult);

        role.save();

    }

    /**
     * 请求更新元宝显示????
     */
    @RequestMapping
    public void updateRoleGoldAndSiver(IoSession session, ReqActivityList reqActivityList) {
//        RoleService roleService = SpringUtils.getBean(RoleService.class);
//        Dao dao = SpringUtils.getBean(Dao.class);
//        Role role = SessionUtils.getRoleBySession(session);
//        if (role == null) {
//            return;
//        }
//        AccountService accountService = SpringUtils.getBean(AccountService.class);
//        Account account = accountService.getAccount(role.getSid());
//        if (account == null) {
//            return;
//        }
//        String userName = account.getUsername();
//        List<Charge> list = dao.query(Charge.class, Cnd.where("userName", "=", userName).and("status", "=", 0));
//        if (list != null && list.size() > 0) {
//            for (Charge charge : list) {
//                if (charge.getStatus() != 0 || charge.getGold() <= 0) {
//                    continue;
//                }
//                // 加金元宝
//                int gold = charge.getGold();
//                if (gold <= 0) {
//                    continue;
//                }
//                int size = dao.count(Pay.class, Cnd.where("orderid", "=", charge.getTradeNo()));
//                if (size > 0) {
//                    charge.setStatus(1);
//                    dao.update(charge, "status");
//                    continue;
//                }
//                charge.setStatus(1);
//                dao.update(charge, "status");
//
//                SpringUtils.getRoleService().addGold(role, gold, Reason.RECHARGE);
//
//                // 赠送抽奖次数
//                MessagePusher.pushMessage(session, new RespMsg("充值成功,获得#R" + gold + "#n元宝。"));
//                int count = charge.getRmb() / 3;
//
//
//                Map<String, Integer> fuliMap = role.getExtendBox().getWelfare();
//                fuliMap.put("lotteryDraw", fuliMap.getOrDefault("lotteryDraw", 0) + count);
//                ///写入充值数据日志t_patdata ///赠送抽奖次数 rmb/3 更新到role fuli
//                String channelcode = account.getChannelCode();
//                // gold/rmb
//                // 插入充值记录
//                String rmb = charge.getRmb() + "";
//                Pay pay = new Pay();
//                pay.setOrderid(charge.getTradeNo());
//                pay.setCreatetime(charge.getTime());
//                pay.setMoney(rmb);
//                pay.setStatus("1");
//                pay.setUserchannel(channelcode);
//                pay.setUserid(account.getUsername());//充值账号id
//                if (Integer.parseInt(rmb) >= 0) {
//                    dao.insert(pay);
//                }
//                // 单笔充值赠送神兽
//            }
//        }
//        roleService.updateRoleGoldAndSiver(role);
//        List<FiedValue> fiedValues = new ArrayList<>();
//        {
//            FiedValue fiedValue = new FiedValue();
//            fiedValue.setType((short) 868);       //重置抽奖次数
//            fiedValue.setVT((byte) 3);
//            fiedValue.setValue(role.getExtendBox().getWelfare().getOrDefault("lotteryDraw", 0));
//            fiedValues.add(fiedValue);
//        }
//        RespUpdate respUpdate = new RespUpdate();
//        respUpdate.setRoleId(role.getRoleId());
//        respUpdate.setList(fiedValues);
//        MessagePusher.pushMessage(role, respUpdate);
//
//        role.save();
        RoleService roleService = SpringUtils.getBean(RoleService.class);
        Role role = SessionUtils.getRoleBySession(session);
        roleService.updateRoleGoldAndSiver(role);
        List<FiedValue> fiedValues = new ArrayList<>();
        {
            FiedValue fiedValue = new FiedValue();
            fiedValue.setType((short) 868);       //重置抽奖次数
            fiedValue.setVT((byte) 3);
            fiedValue.setValue(role.getExtendBox().getWelfare().getOrDefault("lotteryDraw", 0));
            fiedValues.add(fiedValue);
        }
        RespUpdate respUpdate = new RespUpdate();
        respUpdate.setRoleId(role.getRoleId());
        respUpdate.setList(fiedValues);
        MessagePusher.pushMessage(role, respUpdate);
    }

    /**
     * 打开商城
     *
     * @param session
     * @param reqOpenOnlineMall
     */
    @RequestMapping
    public void openMall(IoSession session, ReqOpenOnlineMall reqOpenOnlineMall) {
        Role role = SessionUtils.getRoleBySession(session);
        if (role == null) {
            return;
        }
        RespOnlineMall respOnlineMall = new RespOnlineMall();
        respOnlineMall.setPara(reqOpenOnlineMall.getPara());
        ArrayList<OnlineMallInfo> arrayList = new ArrayList<>();
        for (Map.Entry<String, OnlineMall> entry : DataCache.NUM_MALL.entrySet()) {

            OnlineMall onlineMall = entry.getValue();
            OnlineMallInfo onlineMallInfo = new OnlineMallInfo();
            onlineMallInfo.setName(onlineMall.getName());
            onlineMallInfo.setBarcode(onlineMall.getNumber());
            onlineMallInfo.setFor_sale(onlineMall.getCosttype());
            onlineMallInfo.setPage(onlineMall.getPage());
            onlineMallInfo.setShow_pos(onlineMall.getPos());
            onlineMallInfo.setPrice(onlineMall.getPrice());
            onlineMallInfo.setSale_quota(onlineMall.getXiangou());
            onlineMallInfo.setQuota_limit(onlineMall.getXiangou());
            if (onlineMall.getXiangou() < 0) {
                onlineMallInfo.setDiscountTime(-1);
            } else {
                onlineMallInfo.setDiscountTime(new Long(onlineMall.getTime().getTime() / 1000).intValue());
            }
            onlineMallInfo.setDiscount(onlineMall.getSale());
            arrayList.add(onlineMallInfo);
        }
        respOnlineMall.setList(arrayList);
        MessagePusher.pushMessage(role, respOnlineMall);

        //返回兑换金钱
        List<GoldToMoney> list = new ArrayList<>();
        RespGoldToMoney respGoldToMoney = new RespGoldToMoney();
        respGoldToMoney.setList(list);

        {
            GoldToMoney goldToMoney = new GoldToMoney();
            goldToMoney.setCode("C0000001");
            goldToMoney.setGold(300);
            goldToMoney.setMoney(3000000);
            list.add(goldToMoney);
        }
        {
            GoldToMoney goldToMoney = new GoldToMoney();
            goldToMoney.setCode("C0000002");
            goldToMoney.setGold(600);
            goldToMoney.setMoney(6000000);
            list.add(goldToMoney);
        }
        {
            GoldToMoney goldToMoney = new GoldToMoney();
            goldToMoney.setCode("C0000003");
            goldToMoney.setGold(1100);
            goldToMoney.setMoney(10000000);
            list.add(goldToMoney);
        }
        {
            GoldToMoney goldToMoney = new GoldToMoney();
            goldToMoney.setCode("C0000004");
            goldToMoney.setGold(3300);
            goldToMoney.setMoney(30000000);
            list.add(goldToMoney);
        }
        {
            GoldToMoney goldToMoney = new GoldToMoney();
            goldToMoney.setCode("C0000005");
            goldToMoney.setGold(7200);
            goldToMoney.setMoney(60000000);
            list.add(goldToMoney);
        }
        {
            GoldToMoney goldToMoney = new GoldToMoney();
            goldToMoney.setCode("C0000006");
            goldToMoney.setGold(12000);
            goldToMoney.setMoney(100000000);
            list.add(goldToMoney);
        }
        MessagePusher.pushMessage(role, respGoldToMoney);
    }
}
